<?php

namespace control;

/*
*费用报销记录类
*/

class costClass extends adIndexClass
{
	private const page    = 'cost';
	private const table   = 'cost';
	private const tableMx = 'cost_record';
	private const title   = '费用报销记录';
	public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('cost.home.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'  => [
                        'name'  => L('cost.home.stid'),
                        'width' => 150,
                    ],
                    'deptName'         => [
                        'name'  => L('cost.home.deptName'),
                        'width' => 200,
                    ],
                    'type'          => [
                        'name'  => L('cost.home.type'),
                        'width' => 150,
                    ],
                    'reason'          => [
                        'name'  => L('cost.home.text'),
                        'width' => 300,
                    ],
                    'money'          => [
                        'name'  => L('cost.home.money') . '(' . static::$unit . ')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => L('cost.home.applyDate'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('cost.home.state'),
                        'width' => 120,
                    ],
                    'isPay'          => [
                        'name'  => L('cost.home.isPay'),
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('cost.home.orderNo') => text(array("name" => "orderNo")),
                    L('cost.home.deptName')   => text(array("name" => "deptName")),
                    L('cost.home.text') => text(array("name" => "text")),
                ],
                [
                    L('cost.home.type')  =>  select(["name" => "type", 'option' => explode('，', para('reimburseType'))]),
                    L('cost.home.state') => select(array("name" => "state", "option" => $this->stateOption)),
                    L('cost.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('cost.home.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('cost.home.del') . "</span>\n";
        }
        if ($this->power(self::page, "pay")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'pay', {})\">" . L('cost.home.pay') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"orderNo"  => $this->post('orderNo'),//编号
			"text"     => $this->post('text'),//报销事由
			"deptName" => $this->post('deptName'),//申请人部门
		);
		//全等查询数组
		$equal = array(
			'coid'     => self::$coid,
			"stid"     => $this->post('stid'),//申请人
			"state"    => $this->post('state'),//状态
			"type"     => $this->post('type'),//类型
			"classify" => 2,
		);
		$and   = $this->seeSelf(self::page);
		if ($this->post('createTime')) {
			$timeArr = explode(' ~ ', $this->post('createTime'));
			$and     .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => L('cost.home.detail'), "click" => "newIframe('" . L('cost.home.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'isPay':
                        $row[] = $array['isPay'] == 1 ? L('cost.home.yes') : L('cost.home.no');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $total = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 拨付
	 *
	 * @return bool|string
	 */
	public function pay()
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					L('cost.pay.tips') => L('cost.pay.tipsMsg'),
				),
			)
		));
		//返回
		return $this->layer(array("title" => L('cost.pay.pay'), "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'listForm',));
	}

	/**
	 * 拨付编辑
	 *
	 * @return bool|string
	 */
	public function payEdit()
	{
		$listId = $this->post('listId');
		if (!$this->power(self::page, "pay")) {
			$json['warn'] = L('cost.payEdit.power');
		} elseif (empty($listId) || !is_array($listId)) {
			$json['warn'] = L('cost.payEdit.noChoice');
		} else {
			$x = 0;
			foreach ($listId as $id) {
				$info = query(self::table, " id = '$id'");
				if ($info['state'] == '已通过' && !$info['isPay']) {
					$warn = update(array(
						"table" => self::table,
						"field" => [
							'isPay'   => 1,
							'payDate' => $this->date,
						],
						'where' => " id = '$id'",
					));
					if ($warn == '更新成功') {
						//写入到收支平衡中
						$this->insetProfit($id);
						$x++;
						//添加日志
						$text = str_replace(['{{staffName}}', '{{orderNo}}'], [$this->control['name'], $info['orderNo']], L('cost.payEdit.successLog'));
						$this->logText(["type" => self::page, "text" => $text]);
					}
				} else {
					//添加日志
					$text = str_replace(['{{staffName}}', '{{orderNo}}'], [$this->control['name'], $info['orderNo']], L('cost.payEdit.failLog'));
					$this->logText(["type" => self::page, "text" => $text]);
				}
			}
			//返回
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('cost.payEdit.warn'));
			$json['warn']     = 2;
		}
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id     = $this->post('id') ?: self::getId();
        $info   = query(self::table, " id = '" . $id . "' ");
        $hidden = $info['type'] == '车辆费用' ? '' : 'hidden';
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('cost.edit.recordDate') . "：" => text(["name" => "recordDate", 'class' => 'text', "value" => $info['recordDate'] ?: $this->date]),
                    must . L('cost.edit.type') . "：" => select(["name" => "type", 'change' => 'showTarget', 'class' => 'text', 'title' => L('cost.edit.type'), 'option' => explode('，', para('reimburseType')), "value" => $info['type']]) . "<span id='carId' style='width: 100%' class='{$hidden}'>" . selectMultiple(array('table' => 'car', 'name' => 'targetId', 'field' => "id,concat(shortName,carNo) as name", 'sqlField' => 'name', 'title' => L('cost.edit.car'), 'value' => $info['targetId'], 'sqlId' => 'id')) . "</span>",
                ],
                [
                    must . L('cost.edit.reason') . "：" => textarea(["name" => "reason", 'class' => 'textarea', "value" => $info['reason']]),
                    must . L('cost.edit.bankNum') . "：" => text(["name" => "bankNum", 'class' => 'text', "value" => $info['bankNum']]),
                ],
                [
                    L('cost.edit.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],

            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);
        $html .= <<<eof
<style>
.fs-wrap{
  vertical-align: top !important;
}
</style>
<script>
function showTarget(e){
    let val = e.value;
    console.log(val);
    if (val === '车辆费用'){
        $("#carId").show();
    }else{
         $("#carId").hide();
    }
}
</script>
eof;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }


	public function editEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'type'       => $this->post('type'),
			'reason'     => $this->post('reason'),
			'bankNum'    => $this->post('bankNum'),
			'text'       => $this->post('text'),
			'targetId'   => $this->post('targetId'),
			'recordDate' => $this->post('recordDate'),
			'updateTime' => $this->time,
		];
		$annotation = [
			'type'       => L('cost.edit.type'),
			'reason'     => L('cost.edit.reason'),
			'bankNum'    => L('cost.edit.bankNum'),
			'recordDate' => L('cost.edit.recordDate'),
		];
		$rules      = [
			'type'       => 'required',
			'reason'     => 'required',
			'bankNum'    => 'required',
			'recordDate' => 'required|date',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('cost.editEdit.power');
		} elseif ($field['type'] == '车辆费用' && empty($field['targetId'])) {
			$json['warn'] = L('cost.editEdit.targetId');
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'FYBX' . date('Ymd'),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$department   = query('department', " id = '{$this->controlJob['departmentId']}'");
				$field        = array_merge($field, [
					'id'       => $id,
					'classify' => 2,
					'deptName' => $department['name'],
					'orderNo'  => $userNo,
					'coid'     => self::$coid,
					'stid'     => $this->control['stid'],
					'state'    => '草稿',
					'time'     => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('cost.editEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 审核按钮
	 *
	 * @param $info
	 * @return array
	 */
	public function auditButton($info): array
	{
		$button = [];
		if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
			$button[] = [
				"name"  => L('salesContract.auditButton.start'),
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				'style' => 'li-btn-blue-bg',
				"post"  => [
					"act"  => 'start',
					"id"   => $info['id'],
					'body' => self::encryptDecrypt(json_encode([
						'name'    => '费用报销',
						'table'   => self::table,
						'process' => [
							// 预览函数
							'detail' => [
								'cla' => $this->get('cla'),
								'fun' => 'detail',
							],
							//执行发起时验证函数
							'before' => [
								'cla'  => $this->get('cla'),
								'fun'  => 'commitPre',
								'data' => ['id' => $info['id']],
							],
							//完成发起后执行函数
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
// 审批并判断是否有权限
		if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
			$button[] = [
				"name" => L('salesContract.auditButton.addApprover'),
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name" => L('salesContract.auditButton.transfer'),
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name"  => L('salesContract.auditButton.approval'),
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				// 以下参数固定格式
				"post"  => [
					"act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿', '已通过'],
						],
						// 审核时回调
						'process' => [
							//执行首次审核时验证
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//执行末次审核后处理
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
				'style' => 'li-btn-blue-bg',
			];
		}

		// 撤销审批
		if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $info['isPay'] != 1) {
			$button[] = [
				"name" => L('salesContract.auditButton.cancel'),
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿'],
						],
						'process' => [
							//完成发起后执行函数
							'after' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
		return $button;
	}

	public function commitPre($data)
	{
		$info = query(self::table, "id = '$data[id]'");
		if (static::total(array('table' => self::tableMx, 'where' => "costId = '$info[id]'")) > 0) {
			return true;
		}
		return L('cost.commitPre.fillDetails');
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('cost.detail.empty');
		} else {
			//菜单
			$data = array(
				"id"    => $info['id'],
				"title" => L('cost.detail.title'),
			);

			$button   = [];
			$mxButton = '';//目标按钮
			if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
				//按钮
				$button[] = [
					"name"  => L('cost.detail.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
				];
				$mxButton = "<span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . suiji() . "',mainId:'" . $info['id'] . "'})\">" . L('cost.detail.new') . "</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">" . L('cost.detail.del') . "</span>
                ";
			}
			if ($this->power(self::page, "del") && $info['state'] == '草稿') {
				//按钮
				$button[] = [
					"name" => L('cost.detail.del'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			//审核按钮
			$button = array_merge($button, $this->auditButton($info));

			$result   = find(array('table' => self::tableMx, 'where' => "costId = '$info[id]' order by time asc"));
			$checkAll = $this->checkAll("detailForm", "mxId");
			$tr[]     = [$checkAll, L('cost.detail.moneyType'), L('cost.detail.applyDate'), L('cost.detail.money') . '(' . static::$unit . ')', L('cost.detail.text'), L('cost.detail.file')];
			foreach ($result['array'] as $val) {
				//列表控件
				$dominate   = array(
					"box"  => array("name" => "mxId", "value" => $val['id']),
					"edit" => array("title" => L('cost.detail.edit'), "click" => "layer('" . self::page . "','addMx',{id:'" . $val['id'] . "',mainId:'" . $info['id'] . "'})"),
				);
				$fileResult = find(array('table' => 'file', 'where' => " targetId = '$val[id]' and target = '费用报销' order by time asc"));
				$imgText    = '';
				foreach ($fileResult['array'] as $v) {
					if (in_array($v['format'], ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'])) {
						$img = [
							'preview' => array('title' => $v['name'], 'name' => $v['name'], 'format' => $v['format'], 'href' => $v['src']),
						];
					} else {
						$img = [
							'img' => array('title' => $v['name'], 'href' => $v['src']),
						];
					}
					$imgText .= $this->dominate($img);
				}
				$tr[] = [$this->dominate($dominate), $val['type'], $val['applyDate'], $val['money'], $val['text'], $imgText];
			}
            $total_tr = [
                3  => self::lostZero(array_sum(array_column((array)$result['array'],'money')),'money'),
            ];

			$targetName = '';
			if ($info['type'] == '车辆费用') {
				$target     = query('car', "id = '$info[targetId]'");
				$targetName = $target['shortName'] . $target['carNo'];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				'基本信息' => array(
					array(
						L('cost.detail.orderNo') => $info['orderNo'],
						L('cost.detail.type')    => $info['type'],
						L('cost.detail.reason')  => $info['reason'],
                        L('cost.detail.recordDate') => $info['recordDate'],
					),
					array(
						L('cost.detail.bankNum')  => $info['bankNum'],
						L('cost.detail.deptName') => $info['deptName'],
						L('cost.detail.stid')     => self::findStaff($info['stid']),
                        L('cost.detail.target')     => $targetName,
					),
					array(
						L('cost.detail.time')       => $info['time'],
						L('cost.detail.commitTime') => self::null($info['commitTime']),
						L('cost.detail.state')      => $info['state'],
					),
                    array(
                        L('cost.detail.remark')     => pre($info['text']),
                    ),
				),
			));
            $data['html'] .= $this->detailList([
                'title' => L('cost.detail.costMx'),
                'button' => $mxButton,
                'html' => "
                <div class='purchaseMx'>
                    <form name='detailForm'>" .
                        hidden(array('name' => 'id', 'value' => $info['id'])) .
                        $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)) .
                    "</form>
                </div>
                ",
            ]);
            $data['html'] .= $this->detailBlock([
                L('cost.detail.process') => auditClass::auditRecord(self::table, $info['id'])
            ]);
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 添加明细
	 *
	 * @return bool|string
	 */
	public function addMx()
	{
		$mx = query(self::tableMx, " id = '{$this->post('id')}'");
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					must . L('cost.addMx.type') . "：" => select(array("name" => "type", 'title' => L('cost.addMx.type'), 'option' => explode('，', para('costType')), "value" => $mx['type'])),
				),
				array(
					must . L('cost.addMx.applyDate') . "：" => text(array("name" => "applyDate", 'laydate' => [], "value" => $mx['applyDate'])),
				),
				array(
					must . L('cost.addMx.money') . "：" => text(array("name" => "money", 'unit' => static::$unit, "value" => $mx['money'])),
				),
				array(
					L('cost.addMx.text') . "：" => text(array("name" => "text", 'class' => 'long', "value" => $mx['text'])),
				),
				array(
					L('cost.addMx.file') => fileUploadClass::addFileComponent($mx['id'], '费用报销', self::page, self::page . 'AddMxForm'),
				),
			), 'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId'))),
		));
		//返回
		return $this->layer(array("title" => L('cost.addMx.mx'), "height" => 500, "width" => 800, "html" => $html));
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$fileIdArr = $this->post('fileId');
		$id        = $this->post('id');
		$info      = query(self::table, " id = '{$this->post('mainId')}'");
		$mx        = query(self::tableMx, " id = '$id'");

		$field      = [
			'type'      => $this->post('type'),
			'applyDate' => $this->post('applyDate'),
			'money'     => $this->post('money'),
			'text'      => $this->post('text'),
		];
		$annotation = [
			'type'      => L('cost.addMx.type'),
			'applyDate' => L('cost.addMx.applyDate'),
			'money'     => L('cost.addMx.money'),
		];
		$rules      = [
			'type'      => 'required',
			'applyDate' => 'required',
			'money'     => 'required|numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('cost.addMxEdit.power');
		} elseif (empty($info['id'])) {
			$json['warn'] = L('cost.addMxEdit.empty');
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = L('cost.addMxEdit.stateError');
		} else {
			if (empty($mx['id'])) {
				$field        = array_merge($field, [
					'id'     => $id,
					'costId' => $info['id'],
					'time'   => $this->time,
				]);
				$json['warn'] = insert(array(
					"table" => self::tableMx,
					"field" => $field,
				));
			} else {
				$json['warn'] = update(array(
					"table" => self::tableMx,
					"field" => $field,
					"where" => "id = '$mx[id]'",
				));
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加主表ID到附件表
				if (is_array($fileIdArr)) {
					update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
				}
				$money = find(array('table' => 'cost_record', 'sum' => "money", 'where' => "costId = '$info[id]'"));
				update(array('table' => self::table, 'field' => ['money' => $money], 'where' => "id = '$info[id]'"));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('cost.addMxEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}


	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'delMx':
				$act      = 'del';
				$msg      = L('cost.operate.delMx');
				$title    = self::page . 'DeleteMx';
				$function = 'deleteMx';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				break;
			default:
				$act      = 'del';
				$msg      = L('cost.operate.del');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('cost.operate.warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除明细
	 *
	 * @return bool|string
	 */
	public function deleteMx()
	{
		$array = $this->post('mxId');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('cost.deleteMx.power');
		} elseif (empty($array)) {
			$json['warn'] = L('cost.deleteMx.noChoice');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$mx = query(self::tableMx, " id = '$id' ");
				//最后删除基本参数
				delete(array("table" => self::tableMx, "where" => " id = '$id' "));

				//返回
				$warn = L('cost.deleteMx.success');
				$x++;
				$text .= str_replace(['{{name}}', '{{id}}'], [$mx['type'], $mx['id']], L('cost.deleteMx.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('cost.deleteMx.log')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('cost.deleteMx.warn'));
			$json['warn']     = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('cost.delete.power');
		} elseif (empty($array)) {
			$json['warn'] = L('cost.delete.noChoice');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] != '草稿') {
					$warn = L('cost.delete.stateError');
				} else {
					$mxAll = find(array('table' => self::tableMx, "where" => "costId = '$id'"));
					foreach ($mxAll['array'] as $array) {
						$all = find(array('table' => 'file', 'where' => "targetId = '$array[id]'"));
						foreach ($all['array'] as $val) {
							fileDelete($val['src']);
							delete(array("table" => 'file', "where" => " id = '$val[id]' "));
						}
					}
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					//删除audit表记录
					delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
					//删除待办事项
					delete(array("table" => "backlog", "where" => " typeId = '$id' "));
					//删除审批记录
					delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
					//删除消息提醒
					delete(array("table" => "message", "where" => " typeId = '$id' "));
					//返回
					$warn = L('cost.delete.success');
					$x++;
				}
				$text .= str_replace(['{{id}}'], [$info['id']], L('cost.delete.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('cost.delete.log')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('cost.delete.warn'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 拨付后写入到收支平衡表中
	 */
	public function insetProfit($id)
	{
		$info   = query(self::table, " id = '$id'");
		$result = find(array('table' => self::tableMx, 'where' => " costId = '$info[id]' order by time asc"));
		foreach ($result['array'] as $array) {
			insert(array(
				'table' => 'profit',
				'field' => [
					'id'         => self::getId(),
					'stid'       => $info['stid'],
					'target'     => '费用报销',
					'targetId'   => $array['id'],
					'direction'  => '支出',
					'type'       => $array['type'],
					'money'      => $array['money'],
					'payDate'    => $array['applyDate'],
					'updateTime' => $this->time,
					'time'       => $this->time,
				],
			));
		}
	}
}
